package de.karlNet.sambamanager.view.beans;

import java.util.Iterator;

import javax.faces.event.ActionEvent;

import org.primefaces.event.NodeCollapseEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapController.LdapMemberOfTree;
import de.karlNet.sambamanager.ldapController.LdapMemberTree;
import de.karlNet.sambamanager.ldapModel.LdapObject;

@Controller
public class LdapMemberBean {
	@Autowired
	private LdapMemberTree ldapController;
	private TreeNode root;
	private DefaultTreeNode myRoot;
	private ManualLeafHandlingTreeNode selectedNode;

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public TreeNode getRoot() {
		return root;
	}

	public LdapMemberBean() {
		this.root = new ManualLeafHandlingTreeNode(new LdapObject(
				"example.com", "dc=example,dc=com"), null);
		this.myRoot = new ManualLeafHandlingTreeNode(new LdapObject(
				"example.com", "dc=example,dc=com"), root);
		System.out.println("constructed member bean");
	}

	public void setRoot(ManualLeafHandlingTreeNode root) {
		Iterator<TreeNode> i = this.myRoot.getChildren().iterator();
		while (i.hasNext()) {
			i.next();
			// Use isLeaf() method to check doesn't have childs.
			i.remove();
		}
		this.myRoot.setExpanded(false);
		this.myRoot.setData(this.ldapController.getNewDn(root.getLdapObject()
				.getDn()));
	}

	public void onNodeExpand(NodeExpandEvent event) {
		ManualLeafHandlingTreeNode parent = (ManualLeafHandlingTreeNode) event
				.getTreeNode();
		for (LdapObject ldapObject : this.ldapController.getChildrenOfDN(parent
				.getLdapObject().getDn())) {
			System.out.println(ldapObject.getDn());
			ManualLeafHandlingTreeNode child = new ManualLeafHandlingTreeNode(
					ldapObject, parent);
		}
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = (ManualLeafHandlingTreeNode) selectedNode;
	}

	public void displaySelectedSingle(ActionEvent event) {
	}

	public void onNodeCollapse(NodeCollapseEvent event) {
	}

	public void onNodeSelect(NodeSelectEvent event) {
		this.setSelectedNode(event.getTreeNode());
	}

}
